<template>
    <el-dialog ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="50%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="选择鱼塘" prop="fishPondId">
                <el-select v-model="ruleForm.fishPondId" filterable clearable class="w100p"
                    @change="handleChangeFishPond">
                    <el-option v-for="(item, index) in fishPondList" :key="index" :label="item.pondName"
                        :value="item.fishPondId" />
                </el-select>
            </el-form-item>
            <el-form-item label="选择批次" prop="batchId">
                <el-select v-model="ruleForm.batchId" filterable clearable class="w100p">
                    <el-option v-if="ruleForm.fishPondId == item.fishPondId" v-for="(item, index) in batchList"
                        :key="index" :label="item.batchName" :value="item.batchId" />
                </el-select>
            </el-form-item>
            <el-form-item label="使用称重记录">
                <el-select v-model="ruleForm.isChooseWeighting" class="w100p">
                    <el-option label="去使用" :value="true" />
                    <el-option label="不使用" :value="false" />
                </el-select>
            </el-form-item>
            <el-form-item label="称重记录表" v-show="ruleForm.isChooseWeighting">
                <el-table ref="multipleTableRef" :data="batchWeighingList" height="200" border class="w100p"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="fishVarietyName" label="品种" width="180">
                    </el-table-column>
                    <el-table-column prop="specName" label="规格" width="180">
                    </el-table-column>
                    <el-table-column prop="num" label="尾数(尾)">
                    </el-table-column>
                    <el-table-column prop="weight" label="重量(斤)">
                    </el-table-column>
                </el-table>
            </el-form-item>
            <div v-if="!ruleForm.isChooseWeighting">
                <el-form-item label="选择品种" prop="fishVarietyId">
                    <el-select v-model="ruleForm.fishVarietyId" filterable clearable class="w100p"
                        @change="handleChangeFishVariety">
                        <el-option v-for="item, index in fishVarietyList" :key="index" :label="item.varietyName"
                            :value="item.fishVarietyId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择规格" prop="specificationId">
                    <el-select filterable clearable v-model="ruleForm.specificationId" placeholder="选择规格" class="w100p">
                        <el-option v-if="ruleForm.fishVarietyId == item.fishVarietyId"
                            v-for="item, index in specificationList" :key="index" :label="item.specificationName"
                            :value="item.specificationId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="投塘数量" prop="num">
                    <el-input v-model="ruleForm.num" clearable placeholder="请输入数量" type="number" class="w100p">
                        <template slot="append">尾</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="投塘重量" prop="weight">
                    <el-input v-model="ruleForm.weight" placeholder="请输入重量" clearable type="number" class="w100p">
                        <template slot="append">斤</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="供应商" prop="supplier">
                    <el-input v-model="ruleForm.supplier" clearable placeholder="请输入供应商名称" class="w100p"></el-input>
                </el-form-item>
                <el-form-item label="码单号" prop="codeNumber">
                    <el-input v-model="ruleForm.codeNumber" clearable placeholder="请输入码单号" class="w100p"></el-input>
                </el-form-item>
            </div>
            <el-form-item label="投塘人" prop="staffId">
                <el-select v-model="ruleForm.staffId" filterable clearable class="w100p" @change="handleChangeStaff">
                    <el-option v-for="item, index in staffList" :key="index" :label="item.staffName"
                        :value="item.staffId" />
                </el-select>
            </el-form-item>
            <el-form-item label="投塘日期" prop="inputDate">
                <el-date-picker v-model="ruleForm.inputDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期时间"
                    :picker-options="pickerOptions" class="w100p">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <SaveDraftBox ref="saveDraft" v-if="addEditFlag == 'add' && dialogVisible" :formData="ruleForm" @pushData="pushData">
            </SaveDraftBox>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import pondStockingManagement from '@/api/production-management/pond-stocking-management.js';
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        fishPondList: {
            type: Array,
            default: () => {
                return []
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return []
            }
        },
        fishVarietyList: {
            type: Array,
            default: () => {
                return []
            }
        },
        specificationList: {
            type: Array,
            default: () => {
                return []
            }
        },
        staffList: {
            type: Array,
            default: () => {
                return []
            }
        },
        weighingList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        let checkNum = (rule, value, callback) => {
            if (value) {
                if (Number(value) > 0 && Number(value) <= 99999) {
                    callback();
                } else if (Number(value) > 99999) {
                    callback(new Error('请输入小于100000的数'));
                } else {
                    callback(new Error('请输入大于0的数'));
                }
            } else {
                callback(new Error('请输入数值'));
            }
        };
        return {
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {
                isChooseWeighting:false
            },
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() >= Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            rules: {
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                weight: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                inputDate: [
                    { required: true, message: '请选择投塘时间', trigger: 'change' }
                ],
                fishPondId: [
                    { required: true, message: '请选择鱼塘', trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择投塘人', trigger: 'change' }
                ],
                fishVarietyId: [
                    { required: true, message: '请选择品种', trigger: 'change' }
                ],
                specificationId: [
                    { required: true, message: '请选择品种规格', trigger: 'change' }
                ],
            }
        }
    },
    computed: {
        batchWeighingList() {
            let fishPondId = this.ruleForm.fishPondId;
            let batchId = this.ruleForm.batchId;
            return this.weighingList.filter(item => {
                return item.fishPondId == fishPondId && item.batchId == batchId && !item.inputPondId
            })
        },
    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.addEditApi = pondStockingManagement.add
                this.addEditName = '添加';
                this.getInitRulFormData();
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data }
                this.addEditApi = pondStockingManagement.edit
                this.addEditName = '编辑'
            }
        },
        pushData(data) {
            this.ruleForm = { ...data };
            this.$nextTick(() => {
                this.$refs.ruleForm.clearValidate();
            })
        },
        //初始化一些表单数据
        getInitRulFormData() {
            let staffId = sessionStorage.getItem('staffId') || null;
            let fishPondId = this.data.fishPondId;
            let batchId = this.data.batchId;
            let params = {
                staffId: staffId == 'null' ? '' : Number(staffId),
                fishPondId: fishPondId,
                batchId: batchId,
                inputDate: this.$formatTime(new Date(), 'yyyy-MM-dd')
            }
            this.$set(this, 'ruleForm', params);
            if (this.batchWeighingList.length > 0) {
                this.isChooseWeighting = true
            } else {
                this.isChooseWeighting = false
            }
        },
        handleSelectionChange(v) {
            this.weightRecordIdList = v.map(item => { return item.weightRecordId });
        },
        //选择鱼塘时提示用户是否存在该关联批次
        handleChangeFishPond(id) {
            let rut = this.batchList.find(item => item.fishPondId == id);
            let batchId = rut?.batchId
            this.$set(this.ruleForm, 'batchId', batchId || '');
            !rut && this.$message.warning('该鱼塘暂无批次!');
            if (this.batchWeighingList.length > 0) {
                this.isChooseWeighting = true;
            }
        },
        //选择品种时提示用户是否存在该品种规格
        handleChangeFishVariety(id) {
            let rut = this.specificationList.find(item => item.fishVarietyId == id);
            let specificationId = rut?.specificationId
            this.$set(this.ruleForm, 'specificationId', specificationId || '');
            !rut && this.$message.warning('该鱼种暂未配置规格!');
        },
        //获取姓名
        handleChangeStaff(id) {
            let rut = this.staffList.find(item => item.staffId == id);
            let staffName = rut?.staffName;
            // this.$set(this.ruleForm, 'staffName', staffName || '');
            this.ruleForm.staffName = staffName || ''
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    let param = {}
                    //isChooseWeighting用来判断是否使用了称重记录
                    //如果有 称重记录就带入称重记录id集合；
                    //如果没有 称重记录就带入录入的称重数据；
                    if (this.ruleForm.isChooseWeighting) {
                        if (this.weightRecordIdList.length > 0) {
                            param = {
                                fishPondId: this.ruleForm.fishPondId,
                                batchId: this.ruleForm.batchId,
                                staffId: this.ruleForm.staffId,
                                staffName: this.ruleForm.staffName,
                                inputDate: this.ruleForm.inputDate,
                                weightRecordIdList: this.weightRecordIdList
                            }
                        } else {
                            this.$message.warning('请选择称重记录！');
                            return
                        }
                    } else {
                        param = {
                            ...this.ruleForm,
                            weightRecordIdList: []
                        }
                    }
                    this.addEditApi({ ...param }).then(res => {
                        let msg = res.success ? '操作成功' : '操作失败'
                        this.$message[res.success ? 'success' : 'warning'](res.message || msg)
                        res.success && this.cancel();
                        //提交数据时删除保存的记录
                        res.success && this.addEditFlag == 'add' && this.$refs.saveDraft.delByKey();
                    }).catch(err => {
                        this.$message.error(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.weightRecordIdList = [];
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped></style>